package sisi.vatarticles;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.SuspendNotAllowedException;
import org.zkoss.zk.ui.event.CreateEvent;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.ForwardEvent;
import org.zkoss.zk.ui.sys.ComponentsCtrl;
import org.zkoss.zk.ui.util.ConventionWires;
import org.zkoss.zul.Intbox;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.ListitemRenderer;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Toolbarbutton;
import org.zkoss.zul.Window;

import sisi.General;
import sisi.ListaStandardWindow;


/**
 * VatarticleWindow.java - Controller class for <i>VAT articles window</i>. 
 * @author Pedro Gonzalez pedro@sisisoftware.it
 * @author Claudio Pelosi claudio@sisisoftware.it
 * @author SISI Software S.n.c. - www.sisisoftware.it
 * @version 1.0, 19/11/2013
 * 
 */

@SuppressWarnings({ "rawtypes", "unchecked", "serial" })
public class VatarticleWindow extends Window implements
		org.zkoss.zk.ui.ext.AfterCompose, ListaStandardWindow {
	
	// listbox boxVatarticle
	private Window windowVatarticle, windowEditVatarticle;
	private Textbox tbCerca;
	private Listbox boxVatarticle;

	private List tutti_i_vatarticles;
	private boolean lNuovo;
	private Toolbarbutton buttonSeleziona;

	private ListModelList listModelList;
	private Integer idSelezionato = 0;

	protected Map<String, Object> args;
	private Object vatarticleItem;
	private Vatarticle modVatarticle;
	// edit
	private Intbox id;
	private Textbox article_number, english_description, italian_description, code;

	public void onCreate$windowVatarticle(Event event) {

		CreateEvent ce = (CreateEvent) ((ForwardEvent) event).getOrigin();
		args = (Map<String, Object>) ce.getArg();
		String tastoSeleziona = (String) args.get("tastoSeleziona");
		tastoSeleziona = (tastoSeleziona == null || tastoSeleziona.isEmpty() ? "N"
				: tastoSeleziona);
		boolean lTastoSeleziona = tastoSeleziona.equals("S");
		if (!lTastoSeleziona) {
			buttonSeleziona.setVisible(false);
		}
		idSelezionato = (Integer) args.get("idselezionato");

		listModelList = new ListModelList();
		tutti_i_vatarticles = new VatarticleController().getVatarticleList(null);
		listModelList.addAll(tutti_i_vatarticles);
		boxVatarticle.setModel(listModelList);
		boxVatarticle.setItemRenderer(new VatarticleItemRenderer());
		
		if (idSelezionato!=null && idSelezionato!=0){
			for (int i = 0; i < tutti_i_vatarticles.size(); i++) {
				Vatarticle vatarticle = (Vatarticle)tutti_i_vatarticles.get(i);
				if (vatarticle.getId()==idSelezionato.intValue()){
					boxVatarticle.setSelectedIndex(i);
					break;
				}
			}
		}

	}

	public void afterCompose() {

		// wire variables
		ConventionWires.wireVariables(this, this);

		// auto forward
		ConventionWires.addForwards(this, this);

	}

	public void onOK$tbCerca(Event event){
		cerca();
	}
	
	public void onClick$buttonCerca(Event event) {
		cerca();
	}
	
	
	private void cerca(){
		listModelList = new ListModelList();
		tutti_i_vatarticles = new VatarticleController().getVatarticleList(tbCerca
				.getValue());
		listModelList.addAll(tutti_i_vatarticles);
		boxVatarticle.setModel(listModelList);
		boxVatarticle.setItemRenderer(new VatarticleItemRenderer());		
	}
	
	
	
	public void onDoubleClicked(Event event) {
		if (buttonSeleziona.isVisible()) {
			seleziona();
		} else {
			modifica(false);
		}
	}
	
	
	public void onClick$buttonSeleziona(Event event) {

		seleziona();

	}

	public void seleziona() {
		if (boxVatarticle.getSelectedIndex() >= 0 && buttonSeleziona.isVisible()) {
			Object oVatarticle = boxVatarticle.getSelectedItem().getAttribute(
					"rigaVatarticle");
			String codiceSelezionato = ""+((Vatarticle) oVatarticle).getId();
			Sessions.getCurrent().setAttribute("codiceVatarticleSelezionato",
					codiceSelezionato);
			windowVatarticle.detach();
		}
	}


	@Override
	public void onClick$buttonNuovo(Event event) {
		modifica(true);
	}

	@Override
	public void onClick$buttonModifica(Event event) {
		modifica(false);
	}
	
	private void modifica(boolean nuovo){
		try {

			int nIndex = boxVatarticle.getSelectedIndex();

			if (!nuovo && nIndex == -1) { // nessuna riga selezionata

				Messagebox.show("Select a VAT article to modify", "Information", Messagebox.OK, Messagebox.INFORMATION);

			} else {
				HashMap map = new HashMap();
				if (nuovo){
					map.put("lNuovo", true);
				}
				map.put("boxVatarticle", boxVatarticle);
				Window finestraEditVatarticle = (Window) Executions.createComponents(
						"/editVatarticle.zul", null, map);
				finestraEditVatarticle.doModal();
			}

		} catch (SuspendNotAllowedException e) {
			e.printStackTrace();
		}
	}
	
	
	
	@Override
	public void onClick$buttonCancella(Event event) {
		// TODO Auto-generated method stub
		
	}	

	public class VatarticleItemRenderer implements ListitemRenderer {

		public void render(Listitem li, Object data, int index) {
			
			new Listcell(((Vatarticle) data).getArticleNumber()).setParent(li);
			new Listcell(""+((Vatarticle) data).getEnglishDescription()).setParent(li);
			new Listcell(""+((Vatarticle) data).getItalianDescription()).setParent(li);
			new Listcell(((Vatarticle) data).getCode()).setParent(li); 
			
			li.setAttribute("rigaVatarticle", data);
			ComponentsCtrl.applyForward(li, "onDoubleClick=onDoubleClicked");
		}
	}

	
	
	// EDIT VAT ARTICLE: NEW/MODIFY
	public void onCreate$windowEditVatarticle(Event event) {

		CreateEvent ce = (CreateEvent) ((ForwardEvent) event).getOrigin();
		args = (Map<String, Object>) ce.getArg();
		
		boxVatarticle = (Listbox) args.get("boxVatarticle");

		if (args.containsKey("lNuovo")) {
			lNuovo = true;
		} else {
			lNuovo = false;
		}

		if (!lNuovo) {
			vatarticleItem = boxVatarticle.getSelectedItem().getAttribute("rigaVatarticle");
			modVatarticle = new VatarticleController().refreshVatarticle((Vatarticle) vatarticleItem);
			vatarticleItem = modVatarticle;
			windowEditVatarticle.setTitle("Edit VAT article");
			code.setFocus(true);
			id.setValue(modVatarticle.getId());
			article_number.setValue(modVatarticle.getArticleNumber());
			english_description.setValue(modVatarticle.getEnglishDescription());
			italian_description.setValue(modVatarticle.getItalianDescription());
			code.setValue(modVatarticle.getCode());
		} else {
			windowEditVatarticle.setTitle("New VAT article");
			code.setFocus(true);
		}
	}
	
	public void onClick$btnAnnulla(Event event){
		windowEditVatarticle.detach();
	}
	
	public void onClick$btnConferma(Event event){
		if (lNuovo){
			modVatarticle = new Vatarticle();
		} else {

		}
		String testoMsg = "";
		
		modVatarticle.setId(id.getValue());
		modVatarticle.setArticleNumber(article_number.getValue());
		modVatarticle.setCode(code.getValue());
		modVatarticle.setEnglishDescription(General.toUpperAncheNull(english_description.getValue()));
		modVatarticle.setItalianDescription(General.toUpperAncheNull(italian_description.getValue()));
		
		if (lNuovo){
			new VatarticleController().addVatarticle(modVatarticle);
			testoMsg = "Adding VAT article: "+ General.trimNull( modVatarticle.getArticleNumber() );
		} else {
			new VatarticleController().updateVatarticle(modVatarticle);
			testoMsg = "Updating VAT article: "+ General.trimNull( modVatarticle.getArticleNumber() );			
		}
		
		General.showNotify( testoMsg, windowEditVatarticle);
		
		windowEditVatarticle.detach();
		
		// aggiorna listbox
		
		if (lNuovo){
			ListModelList lml = (ListModelList) boxVatarticle.getListModel();
			lml.add(modVatarticle);
			boxVatarticle.setSelectedIndex(lml.indexOf(modVatarticle));
		} else {
			ListModelList lml = (ListModelList) boxVatarticle.getListModel();
			Object oVatarticleItem = boxVatarticle.getSelectedItem().getAttribute("rigaVatarticle");
			if (lml.indexOf(oVatarticleItem) == -1) {
				// non trovato... quindi non lo aggiorno
			} else {
				lml.set(lml.indexOf(oVatarticleItem), modVatarticle);
			}
		}		
	}
	
	
}
